package com.yutong.fmp.legal.utils.reactor.event.generateCaseInfoDucument.utils;

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yutong.fmp.common.core.result.Result;
import com.yutong.fmp.common.core.utils.FileUtils;
import com.yutong.fmp.common.core.utils.FreemarkerUtils;
import com.yutong.fmp.common.core.utils.StringUtils;
import com.yutong.fmp.common.core.utils.UUIDUtil;
import com.yutong.fmp.common.redis.service.RedisService;
import com.yutong.fmp.dict.dictionary.entity.vo.DictVo;
import com.yutong.fmp.dict.dictionary.feign.DictFeign;
import com.yutong.fmp.legal.cases.entity.LegalCaseCheck;
import com.yutong.fmp.legal.cases.entity.LegalCaseCont;
import com.yutong.fmp.legal.cases.entity.LegalCaseInfo;
import com.yutong.fmp.legal.cases.entity.PlainTiff;
import com.yutong.fmp.legal.cases.mapper.LegalCaseCheckMapper;
import com.yutong.fmp.legal.cases.mapper.LegalCaseContMapper;
import com.yutong.fmp.legal.cases.mapper.PlainTiffMapper;
import com.yutong.fmp.legal.coagency.entity.LegalCourt;
import com.yutong.fmp.legal.coagency.entity.LegalLawyer;
import com.yutong.fmp.legal.coagency.entity.LegalLawyerFirm;
import com.yutong.fmp.legal.coagency.mapper.LegalCourtMapper;
import com.yutong.fmp.legal.coagency.mapper.LegalLawyerFirmMapper;
import com.yutong.fmp.legal.coagency.mapper.LegalLawyerMapper;
import com.yutong.fmp.legal.cus.entity.LegalCusInfo;
import com.yutong.fmp.legal.cus.mapper.LegalCusInfoMapper;
import com.yutong.fmp.legal.datalist.entity.LegalDataListTemplate;
import com.yutong.fmp.legal.datalist.entity.LegalDataListTemplateExample;
import com.yutong.fmp.legal.datalist.entity.LegalDataListTemplateExample.Criteria;
import com.yutong.fmp.legal.datalist.entity.LegalDateListDetail;
import com.yutong.fmp.legal.datalist.entity.LegalDateListDetailExample;
import com.yutong.fmp.legal.datalist.entity.vo.LegalDataListDetailVo;
import com.yutong.fmp.legal.datalist.mapper.LegalDataListDetailMapper;
import com.yutong.fmp.legal.datalist.mapper.LegalDataListTemplateMapper;
import com.yutong.fmp.legal.send.entity.LegalSendRecord;
import com.yutong.fmp.legal.send.entity.LegalSendRecord.LegalSendRecordBuilder;
import com.yutong.fmp.legal.service.file.entity.AttFile;
import com.yutong.fmp.legal.service.file.feign.AttFileFeign;
import com.yutong.fmp.legal.service.scfs.entity.dto.SCFSInGetOrderResultDto;
import com.yutong.fmp.legal.service.scfs.entity.result.SCFSResult;
import com.yutong.fmp.legal.service.scfs.feign.FMPSCFSINFegin;
import com.yutong.fmp.legal.utils.LegalConstant;
import com.yutong.fmp.legal.utils.LegalLocalCache;
import com.yutong.fmp.legal.utils.MapUtils;
import com.yutong.fmp.legal.utils.ResultUtils;
import com.yutong.fmp.legal.utils.reactor.event.generateCaseInfoDucument.entity.PlainTiffDocumentPathPojo;
import com.yutong.fmp.legal.utils.retry.RetryHandle;
import lombok.extern.slf4j.Slf4j;

/**
 * 生成资料清单参数组件工具类
 * 
 * @author bkszkjb07
 *
 */
@Slf4j
@Component
public class CaseInfoGenerateDocumentParamUtil {

	@Autowired
	private LegalCourtMapper legalCourtMapper;

	@Autowired
	private LegalCusInfoMapper legalCusInfoMapper;

	@Autowired
	private LegalDataListDetailMapper legalDataListDetailMapper;

	@Autowired
	private LegalDataListTemplateMapper legalDataListTemplateMapper;

	@Autowired
	private PlainTiffMapper plainTiffMapper;

	@Autowired
	private LegalLawyerMapper legalLawyerMapper;

	@Autowired
	private AttFileFeign attFileFeign;

	@Autowired
	private DictFeign dictFeign;

	@Autowired
	private LegalCaseCheckMapper legalCaseCheckMapper;

	@Autowired
	private FMPSCFSINFegin fMPSCFSINFegin;

	@Autowired
	private LegalCaseContMapper legalCaseContMapper;

	@Autowired
	private RedisService redisService;

	@Autowired
	private RetryHandle<SCFSInGetOrderResultDto> retryHandle;
	
	@Autowired
	private LegalLawyerFirmMapper legalLawyerFirmMapper;

	// 设置违约金
	public CaseInfoGenerateDocumentParamUtil settingDefaultMoney(LegalCaseInfo caseInfo, Map<String, Object> params) {
		params.compute("defaultMoney", (k, v) -> {
			if (caseInfo.getFalsifyFee() == null)
				return "_____";
			return caseInfo.getFalsifyFee() == 0 ? "_____" : caseInfo.getFalsifyFee();
		});
		return this;
	}

	// 设置第一个被告名字
	public CaseInfoGenerateDocumentParamUtil settingFirstDefendantName(List<LegalCusInfo> findByIdList,
			Map<String, Object> params) {
		params.compute("defendantFirstName", (k, v) -> {
			if (CollectionUtils.isEmpty(findByIdList))
				return "_____________";
			else {
				return findByIdList.get(0).getCusName();
			}
		});
		return this;
	}

	// 设置被告除第一个被告的其他被告名字
	public CaseInfoGenerateDocumentParamUtil settingOutFirstDefendantNames(List<LegalCusInfo> findByIdList,
			Map<String, Object> params) {
		params.compute("defendantNames", (k, v) -> {
			if (CollectionUtils.isEmpty(findByIdList))
				return "_____________";
			else {
				findByIdList.remove(0);
				return findByIdList.stream().map(LegalCusInfo::getCusName).collect(Collectors.joining(","));
			}
		});
		return this;
	}

	// 设置被告总数量
	public CaseInfoGenerateDocumentParamUtil settingDefendantTotalNum(List<LegalCusInfo> findByIdList,
			Map<String, Object> params) {
		params.compute("defendantTotalNum", (k, v) -> {
			if (CollectionUtils.isEmpty(findByIdList))
				return "_____________";
			else {
				return findByIdList.size();
			}
		});
		return this;
	}

	// 设置所有被告的名字以及名字跟证件号的拼写
	public CaseInfoGenerateDocumentParamUtil settingAllDefendantNamesAndIdNums(List<LegalCusInfo> findByIdList,
			Map<String, Object> params) {
		AtomicReference<String> defendantNamesAndIdNum = new AtomicReference();
		defendantNamesAndIdNum.set("");
		String defendantNamesStr = findByIdList.parallelStream().map((v) -> {
			String strName = "";
			String idNum = "";
			if (StringUtils.isNotBlank(v.getCusName())) {
				strName = v.getCusName();
				if (StringUtils.equals(v.getCusType(), "1")) {
					idNum = v.getRepIdNum();
					if (StringUtils.isBlank(idNum)) {
						idNum = v.getIdNum();
					}
				} else {
					idNum = v.getIdNum();
				}
			} else {
				idNum = "_________________";
				strName = "___________________";
			}

			defendantNamesAndIdNum.getAndAccumulate((strName + "(" + idNum + ")"), (oldS, newS) -> {
				if (StringUtils.isBlank(oldS)) {
					return newS;
				} else {
					return oldS + "," + newS;
				}
			});

			return strName;
		}).collect(Collectors.joining(","));

		params.put("defendantAllNames", defendantNamesStr);
		params.put("defendantNamesAndIdNums", defendantNamesAndIdNum.get());
		// 证件号归约
		return this;
	}

	// 设置被告
	public CaseInfoGenerateDocumentParamUtil settingDefendant(List<LegalCusInfo> findByIdList,
			Map<String, Object> params) {

		params.compute("defendantList", (k, v) -> {
			List<Object> defendantList = Lists.newArrayList();

			if (CollectionUtils.isEmpty(findByIdList))
				return defendantList;
			else {
				DictVo dictVo = new DictVo();
				dictVo.setName("legal_nation");
				Result<List<DictVo>> dict = dictFeign.getDict(dictVo);
				List<DictVo> nationList = Lists.newArrayList();

				if (ResultUtils.isOk(dict)) {
					nationList = dict.getData();
				}

				for (LegalCusInfo cusInfo : findByIdList) {
					HashMap<Object, Object> newHashMap = Maps.newHashMap();
					// 判断法人还是自然人 1自然人 2法人/组织
					newHashMap.put("defendantName", cusInfo.getCusName());
					newHashMap.put("defendantSex", StringUtils.equals(cusInfo.getSex(), "0") ? "男" : "女");
					newHashMap.put("defendantNation", "_____");
					if (CollectionUtils.isNotEmpty(nationList)) {
						for (DictVo vo : nationList) {
							if (StringUtils.equals(vo.getValue(), cusInfo.getNation())) {
								newHashMap.put("defendantNation", vo.getLabel());
							}
						}
					}

					newHashMap.put("defendantBirthday", parseBirthdayByIdNum(cusInfo.getIdNum()));
					newHashMap.put("defendantAddress", cusInfo.getResidence());
					newHashMap.put("defendantIdNum", cusInfo.getIdNum());
					newHashMap.put("defendantPhone", "________________");
					if (StringUtils.equals(cusInfo.getCusType(), "1")) {
						newHashMap.put("defendantRepresentative", cusInfo.getRepName());
						newHashMap.put("defendantCode", cusInfo.getRepIdNum());
						newHashMap.compute("defendantAddress", (key, value) -> {
							if (StringUtils.isBlank(value.toString())) {
								if (StringUtils.isBlank(cusInfo.getRepAddress()))
									return "_________________";
								else
									return cusInfo.getRepAddress();
							} else
								return value;

						});
					}

					defendantList.add(newHashMap);
				}
				return defendantList;
			}
		});
		return this;
	}

	// 设置主办律师，相关律师
	public CaseInfoGenerateDocumentParamUtil setLeadLawyerAndRelateLawyer(LegalCaseInfo caseInfo,
			Map<String, Object> params) {
		String leadLawyerId = caseInfo.getLeadLawyerId();
		String relateLawyerId = caseInfo.getRelateLawyerId();
		System.out.println();
		List<String> leadLawyerIds = Lists.newArrayList();
		List<String> relateLawyerIds = Lists.newArrayList();
		List<LegalLawyer> totalLawyer = Lists.newArrayList();

		if (StringUtils.isNotBlank(leadLawyerId)) {
			if (leadLawyerId.contains(",")) {
				leadLawyerIds = Arrays.asList(leadLawyerId.split(","));
			} else {
				leadLawyerIds.add(leadLawyerId);
			}
			if (CollectionUtils.isNotEmpty(leadLawyerIds)) {
				List<LegalLawyer> legalLawyers = (List<LegalLawyer>) LegalLocalCache.get(caseInfo.getCaseNo(),
						"leadLawyers");
				if (legalLawyers == null) {
					legalLawyers = legalLawyerMapper.findByIdList(leadLawyerIds);
					if (CollectionUtils.isEmpty(legalLawyers))
						Assert.state(false, " 生成文档查询相关律师律师为空" + leadLawyerIds);
					else {
						LegalLocalCache.put(caseInfo.getCaseNo(), "leadLawyers", legalLawyers);
					}
				}
				totalLawyer.addAll(legalLawyers);
			}

		}

		if (StringUtils.isNotBlank(relateLawyerId)) {
			if (relateLawyerId.contains(",")) {
				relateLawyerIds = Arrays.asList(relateLawyerId.split(","));
			} else {
				relateLawyerIds.add(relateLawyerId);
			}
			if (CollectionUtils.isNotEmpty(relateLawyerIds)) {
				List<LegalLawyer> relateLawyers = (List<LegalLawyer>) LegalLocalCache.get(caseInfo.getCaseNo(),
						"relateLawyers");
				if (relateLawyers == null) {
					relateLawyers = legalLawyerMapper.findByIdList(relateLawyerIds);
					if (CollectionUtils.isEmpty(relateLawyers))
						Assert.state(false, " 生成文档查询承办律师为空" + relateLawyerIds);
					else {
						LegalLocalCache.put(caseInfo.getCaseNo(), "leadLawyers", relateLawyers);
					}
				}
				totalLawyer.addAll(relateLawyers);
			}
		}

		params.compute("lawyerList", (key, value) -> {
			return totalLawyer.parallelStream().map((v) -> {
				Map<String, Object> itemmap = Maps.newHashMap();
				itemmap.compute("lawyerName", (a, b) -> {
					if (StringUtils.isBlank(v.getLawyerName()))
						return "__________";
					else
						return v.getLawyerName();
				});

				itemmap.put("lawyerSex", "男");

				itemmap.compute("lawyerPhone", (a, b) -> {
					if (StringUtils.isBlank(v.getLawyerTel()))
						return "__________";
					else
						return v.getLawyerTel();
				});

				return itemmap;
			}).collect(Collectors.toList());
		});

		return this;
	}

	// 设置法院
	public CaseInfoGenerateDocumentParamUtil settingCourtName(LegalCaseInfo caseInfo, Map<String, Object> params) {
		params.compute("courtName", (k, v) -> {
			if (StringUtils.isNotBlank(caseInfo.getLawsuitCourt())) {
				String lawsuitCourtId = caseInfo.getLawsuitCourt();

				LegalCourt legalCourt = legalCourtMapper.findById(lawsuitCourtId);
				if (legalCourt == null)
					return "_____";

				if (StringUtils.isNotBlank(legalCourt.getCourtName())) {
					return legalCourt.getCourtName();
				} else
					return "_____";

			} else
				return "_____";
		});
		return this;
	}

	// 案件考核中的判决/调解完成时间
	public CaseInfoGenerateDocumentParamUtil settingsentenceDate(String caseNo, Map<String, Object> params) {
		params.compute("sentenceDate", (k, v) -> {
			if (StringUtils.isBlank(caseNo))
				return "________";
			LegalCaseCheck legalCaseCheck = new LegalCaseCheck();
			legalCaseCheck.setCaseNo(caseNo);
			legalCaseCheck.setCheckStages(new String[] { "3" });
			List<LegalCaseCheck> findAll = legalCaseCheckMapper.findAll(legalCaseCheck);
			if (CollectionUtils.isEmpty(findAll))
				return "________";
			return findAll.get(0).getEndDate() == null ? "_______"
					: LegalConstant.FORMAT3.format(findAll.get(0).getEndDate());
		});
		return this;
	}

	// 文档生成时间
	public CaseInfoGenerateDocumentParamUtil settingGenerateDate(Map<String, Object> params) {
		params.compute("generateDate", (k, v) -> {
			return LegalConstant.FORMAT3.format(new Date());
		});
		return this;
	}

	// 案件法院号
	public CaseInfoGenerateDocumentParamUtil settingCourtCaseNo(LegalCaseInfo caseInfo, Map<String, Object> params) {
		params.compute("courtCaseNo", (k, v) -> {
			if (StringUtils.isNotBlank(caseInfo.getCourtCaseNo())) {
				String[] split = caseInfo.getCourtCaseNo().split("\\|");
				return split[split.length - 1].toString();
			} else
				return "____________";
		});
		return this;
	}

	// 设置原告住所
	public CaseInfoGenerateDocumentParamUtil settingAddress(PlainTiff plainTiff, Map<String, Object> params) {
		params.compute("plaintiffAddress", (k, v) -> {
			if (StringUtils.isNotBlank(plainTiff.getAddress()))
				return plainTiff.getAddress();
			else
				return "_______";
		});
		return this;
	}

	// 设置案件类型
	public CaseInfoGenerateDocumentParamUtil settingCaseTypeName(String caseTypeNo, Map<String, Object> params) {
		params.compute("caseTypeName", (k, v) -> {
			if (StringUtils.isNotBlank(caseTypeNo))
				if (StringUtils.equals(caseTypeNo, "01")) { // 借款合同纠纷
					return "借款合同纠纷";
				} else if (StringUtils.equals(caseTypeNo, "02")) { // 保理合同纠纷
					return "保理合同纠纷";
				} else if (StringUtils.equals(caseTypeNo, "03")) { // 劳动仲裁
					return "劳动仲裁";
				} else if (StringUtils.equals(caseTypeNo, "04")) { // 融资租赁合同纠纷
					return "融资租赁合同纠纷";
				} else if (StringUtils.equals(caseTypeNo, "05")) { // 追偿权纠纷
					return "追偿权纠纷";
				} else if (StringUtils.equals(caseTypeNo, "06")) { // 其他合同纠纷
					return "其他合同纠纷";
				} else
					return "_______";
			else
				return "_______";
		});
		return this;
	}

	// 设置原告法定代表人
	public CaseInfoGenerateDocumentParamUtil settingRepresentative(PlainTiff plainTiff, Map<String, Object> params) {
		params.compute("plaintiffRepresentative", (k, v) -> {
			if (StringUtils.isNotBlank(plainTiff.getLegalEputy()))
				return plainTiff.getLegalEputy();
			else
				return "_______";
		});
		return this;
	}

	// 设置原告法定代表人身份证号
	public CaseInfoGenerateDocumentParamUtil settingPlaintiffIdNum(PlainTiff plainTiff, Map<String, Object> params) {
		params.compute("plaintiffIdNum", (k, v) -> {
			if (StringUtils.isNotBlank(plainTiff.getIdNo()))
				return plainTiff.getIdNo();
			else
				return "_______";
		});
		return this;
	}

	// 设置原告名称
	public CaseInfoGenerateDocumentParamUtil settingPlaintiff(PlainTiff plainTiff, Map<String, Object> params) {
		params.compute("plaintiffFullName", (k, v) -> {
			if (StringUtils.isNotBlank(plainTiff.getFullName()))
				return plainTiff.getFullName();
			else
				return "_______";
		});
		return this;
	}

	// 设置原告统一引用社代码
	public CaseInfoGenerateDocumentParamUtil setttingPlaintiffCode(PlainTiff plainTiff, Map<String, Object> params) {
		params.compute("plaintiffCode", (key, value) -> {
			if (StringUtils.isNotBlank(plainTiff.getCreditCode()))
				return plainTiff.getCreditCode();
			else
				return "_________________";
		});
		return this;
	}

	// 设置SCFS参数  CASE202003100001 CASE201912250002
	public CaseInfoGenerateDocumentParamUtil settingSCFSValue(String caseNo, Map<String, Object> params) {
		//根据案件号查询合同
		LegalCaseCont legalCaseCont=new LegalCaseCont();
		legalCaseCont.setCaseNo(caseNo);
		List<LegalCaseCont> contList = legalCaseContMapper.findAll(legalCaseCont);
		if(CollectionUtils.isEmpty(contList)) {
			log.error(" 根据{}  生成文档时  查询合同为空  无法获取SCFS 参数 ",caseNo);
			return this;
		}
		MapUtils bulid = MapUtils.bulid();
		
		contList.forEach((value)->{
			if(StringUtils.isNotBlank(value.getContNo())) {
				SCFSInGetOrderResultDto getOrderData=null;
				try {
					
					getOrderData = retryHandle.handle(new RetryHandle.RetryFlow<SCFSInGetOrderResultDto>() {
						
						@Override
						public LegalSendRecord insertRequestRecord(String resultBody) {
							LegalSendRecordBuilder sendRecordBuilder = LegalSendRecord.builder()
									.caseNo(caseNo)
									.keyWords(" getOrderData 合同号 "+value.getContNo())
									.methodMessage("调用 scfs 根据合同号 "+value.getContNo()+"查询案件 ")
									.methodName("CaseInfoGenerateDocumentParamUtil.seetingSCFSValue")
									.sendUrl("FMP-SCFS-IN")
									.returnBody(resultBody);
							return sendRecordBuilder.build();
						}
						
						@Override
						public String generateSendId() {
							return UUIDUtil.getUUID();
						}
						
						@Override
						public Supplier<Result<SCFSInGetOrderResultDto>> exeRquest() {
							Supplier<Result<SCFSInGetOrderResultDto>> supplier = null;
							try {
								supplier=()->{ 
									SCFSResult<SCFSInGetOrderResultDto> temResult=fMPSCFSINFegin.getOrderData(bulid.put("contractNum", value.getContNo()));
									temResult.setMsg(temResult.getMessage());
									return temResult;
								};
							} catch (Exception e) {
								log.error("调用 scfs 根据合同号查询案件 接口异常 {}",e.getMessage());
								throw new RuntimeException(ExceptionUtils.getFullStackTrace(e));
							}
							return supplier;
						}
						
						@Override
						public Map<String, Object> enableRetry(Supplier<Result<SCFSInGetOrderResultDto>> exeRquest, MapUtils param) {
							//发起重试
						   param.put("caseNo", caseNo)
								.put("methodName", "CaseInfoGenerateDocumentParamUtil.seetingSCFSValue")
								.put("methodMessage", "调用 scfs 根据合同号 "+value.getContNo()+"查询案件 ")
								.put("retryMessage", " getOrderData 合同号 "+value.getContNo())
								.put("retryStrategy", "2")
								.put("body", MapUtils.bulid()
										                     .put("executeMethod", exeRquest)
										                     .put("reflectionHandleResult", ResultUtils.getInstance()) //结果
							);
							return param;
						}

						@Override
						public void success(Result<SCFSInGetOrderResultDto> result) {
							//用于数据备份  防止接口调用不通时 获取最后一次缓存的数据替补数据 防止此功能因为第三方问题不能使用
							redisService.hset(LegalConstant.LEGAL_REDIS_SCFS_GETORDERDATAAPI_KEY, value.getContNo(), result.getData(),60*60*12*30);
						}
					  
					});
				} catch (Exception e) {
					getOrderData=(SCFSInGetOrderResultDto) redisService.hget(LegalConstant.LEGAL_REDIS_SCFS_GETORDERDATAAPI_KEY, value.getContNo());
				}
				
				if(getOrderData!=null) {
					System.err.println(" 调用成功 ---- "+getOrderData);
				}
			}
		});
		
		return this;
	}

	//设置律师跟律所信息
	public CaseInfoGenerateDocumentParamUtil settingAssignLawyer(String caseNo,Map<String, Object> params,LegalCaseInfo caseInfo) {
		if(StringUtils.isBlank(caseNo))
			return this;
		//律师userid  在是执行阶段否启用生成调查令的时候已经存放到redis中
		Object hget = redisService.hget(LegalConstant.LEGAL_REDIS_ENABLE_GENERATE_BQ_DCL_DOCUMENT, caseNo);
		String lawyerUserId="";
		if(hget==null) {
			//根据案件号查询第一个主承办律师
			if(caseInfo==null)
				return this;
			String leadLawyerIds = caseInfo.getLeadLawyerId();
			if(StringUtils.isBlank(leadLawyerIds))
				return this;
			
			lawyerUserId = leadLawyerIds.split(",")[0];
		}else
			lawyerUserId=hget.toString();
		
		LegalLawyer lawyerInfo = legalLawyerMapper.findLawyerInfoByUserId(lawyerUserId);
		if(lawyerInfo==null) {
			log.error(" 生成调查令  根据律师userid {} 查询律师为为空 ",lawyerUserId);
			return this;
		}
			
		params.compute("lawyerName", (k,v)->{
			if(StringUtils.isNotBlank(lawyerInfo.getLawyerName()))
				return lawyerInfo.getLawyerName();
			else
				return "_______";
			
		});
		
		params.compute("lawyerIdNo", (k,v)->{
			if(StringUtils.isNotBlank(lawyerInfo.getLawyerIdNo()))
				return lawyerInfo.getLawyerIdNo();
			else
				return "_______";
			
		});
		
		//设置律所名称 
		if(caseInfo==null) 
			return this;
		
		String lawyerFirmId = lawyerInfo.getLawyerFirmId();
		LegalLawyerFirm lawyerFirm = legalLawyerFirmMapper.findById(lawyerFirmId);
		if(lawyerFirm==null)
			return this;
		
		params.compute("lawyerFirmName", (k,v)->{
			if(StringUtils.isNotBlank(lawyerFirm.getLawyerFirmName()))
				return lawyerFirm.getLawyerFirmName();
			else
				return "_______";
			
		});
		
		params.compute("lawyerFirmArea", (k,v)->{
			if(StringUtils.isNotBlank(lawyerFirm.getArea()))
				return lawyerFirm.getArea();
			else
				return "_______";
			
		});
		
		return this;
	}
	
	/*******************************************************************************************************************************************/

	// 根据身份证解析出生日期字符串
	public String parseBirthdayByIdNum(String idNum) {
		if (idNum.length() > 13) {
			String year = idNum.substring(6, 10);
			String month = idNum.substring(10, 12);
			String day = idNum.substring(12, 14);
			return year + "年" + month + "月" + day + "日";
		}
		return "____年__月__日";

	}

	public String queryDateListDetailIdByStageNameAndDetailName(String stageName, String detailName, String caseNo) {
		if (legalDataListDetailMapper == null) {
			Assert.state(false, "查询资料清单legalDataListDetailMapper不存在 不能继续下一步生成文档");
			return "";
		}
		LegalDataListDetailVo vo = new LegalDataListDetailVo();
		vo.setStageName(stageName);
		vo.setDetailName(detailName);
		vo.setCaseNo(caseNo);

		LegalDataListTemplateExample legalDataListTemplateExample = new LegalDataListTemplateExample();
		Criteria createCriteria = legalDataListTemplateExample.createCriteria();
		createCriteria.andStageNameEqualTo(stageName);
		createCriteria.andDetailNameEqualTo(detailName);
		List<LegalDataListTemplate> dataListTemplate = legalDataListTemplateMapper
				.selectByExample(legalDataListTemplateExample);

		if (CollectionUtils.isEmpty(dataListTemplate))
			Assert.state(false, "查询资料清单模板结果不存在 不能继续下一步生成文档");

		LegalDataListTemplate legalDataListTemplate = dataListTemplate.get(0);

		LegalDateListDetailExample dateListDetailExample = new LegalDateListDetailExample();
		com.yutong.fmp.legal.datalist.entity.LegalDateListDetailExample.Criteria createCriteria2 = dateListDetailExample
				.createCriteria();
		createCriteria2.andDataListIdEqualTo(legalDataListTemplate.getFdId());
		createCriteria2.andCaseNoEqualTo(caseNo);
		List<LegalDateListDetail> dataListDetailList = legalDataListDetailMapper.selectByExample(dateListDetailExample);

		if (CollectionUtils.isEmpty(dataListDetailList))
			Assert.state(false, "查询资料清单结果不存在 不能继续下一步生成文档");

		LegalDateListDetail legalDateListDetail = dataListDetailList.get(0);

		return legalDateListDetail.getFdId();
	}

	// 查询所有被告
	public List<LegalCusInfo> queryAllDefendantByCaseInfo(LegalCaseInfo caseInfo) {
		if (StringUtils.isNotBlank(caseInfo.getDefendantId())) {
			List<String> defendantIds = null;
			List<String> defendantNames = null;
			if (caseInfo.getDefendantId().contains(",")) {
				defendantIds = Arrays.asList(caseInfo.getDefendantId().split(","));
				defendantNames = Arrays.asList(caseInfo.getDefendantName().split(","));
			} else {
				defendantIds = Arrays.asList(caseInfo.getDefendantId());
				defendantNames = Arrays.asList(caseInfo.getDefendantName());
			}

			// 查询所有的被告 并且排序
			List<LegalCusInfo> data = Lists.newArrayList();
			List<LegalCusInfo> findByIdList = legalCusInfoMapper.findByIdList(defendantIds);
			for (String name : defendantNames) {
				for (LegalCusInfo item : findByIdList) {
					if (item.getCusName().equals(name)) {
						data.add(item);
					}
				}
			}

			return data;
		} else
			return Lists.newArrayList();
	}

	public void generateAndUpload(Map<String, Object> params, String templateName, String fileName, String fdTargetId,
			String fdFolderName, Integer fdOrder) {
		// 生成文件
		File file = FreemarkerUtils.createDoc(params, "/templates/ftl/datalist", templateName, LegalConstant.filePath,
				fileName);

		// 先判断原来是否有文件 有的话先删除
		LegalDateListDetail legalDateListDetail = legalDataListDetailMapper.selectByPrimaryKey(fdTargetId);
		if (StringUtils.isNotBlank(legalDateListDetail.getDocumentPath())) {
			attFileFeign.delFile(legalDateListDetail.getDocumentPath());
		}

		// 上传到附件服务器
		MultipartFile multipartFile = FileUtils.getMultipartFile(file);
		log.error("上传参数, {}, {} ,{}, {} ,", multipartFile, fdTargetId, fdFolderName, fdOrder);
		Result<AttFile> attFileResult = attFileFeign.uploadFile(multipartFile, fdTargetId, fdFolderName, fdOrder + "");
		log.error("attFileResult{}", attFileResult);
		if (attFileResult.getCode() == 200) {
			AttFile attFile = attFileResult.getData();

			// 更新资料清单
			legalDateListDetail.setDocumentName(attFile.getFdFileName());
			legalDateListDetail.setDocumentPath(attFile.getFdId());
			legalDataListDetailMapper.updateByPrimaryKeySelective(legalDateListDetail);

			attFile.setFdOrder(fdOrder);
			attFileFeign.update(attFile);
		}
		// 删除附件
		file.delete();
	}

	/**
	 * 清除整个案件的数据缓存
	 */
	public void clearCache(String caseNo) {
		LegalLocalCache.clear(caseNo);
	}

	public PlainTiff getPlainTiffByCaseNo(LegalCaseInfo caseInfo) {
		PlainTiff plainTiff = null;
		// 临时缓存减少单个案子生成不同的文书反复查询数据库 单个案子生成结束手动清空
		// 查询这个案子的原告信息
		if (plainTiff == null) {
			plainTiff = LegalLocalCache.getPlainTiff(caseInfo.getCaseNo());
			if (plainTiff == null) {
				plainTiff = plainTiffMapper.findById(caseInfo.getPlaintiff());
				if (plainTiff != null)
					LegalLocalCache.putPlainTiff(caseInfo.getCaseNo(), plainTiff);
			}
		}
		return plainTiff;
	}

	public List<LegalCusInfo> getAllDefendantByCaseNo(LegalCaseInfo caseInfo) {
		List<LegalCusInfo> queryAllDefendant = null;
		if (queryAllDefendant == null || CollectionUtils.isEmpty(queryAllDefendant)) {
			queryAllDefendant = LegalLocalCache.getAllDefendant(caseInfo.getCaseNo());
			if (queryAllDefendant == null) {
				queryAllDefendant = this.queryAllDefendantByCaseInfo(caseInfo);
				if (queryAllDefendant != null & !CollectionUtils.isEmpty(queryAllDefendant)) {
					LegalLocalCache.putAllDefendant(caseInfo.getCaseNo(), queryAllDefendant);
				}
			}
		}
		return queryAllDefendant;
	}

	/*
	 * 根据原告查询身上对应的营业执照，法定代表人身份证明，法定代表人身份证复印件 这里有一个需求是原告身上挂载的这些文档相当于备份文档
	 * 资料清单的可以随时修改不影响原告身上的文档
	 */
	public PlainTiffDocumentPathPojo queryPlainTiffDocument(String plaintiffFdId) {
		PlainTiffDocumentPathPojo ducument = new PlainTiffDocumentPathPojo();
		ducument.setPlainTiffFdID(plaintiffFdId);
		AttFile file = new AttFile();
		file.setFdTargetId(plaintiffFdId);
		// 查询营业执照
		file.setFdFolderName(PlainTiffDocumentPathPojo.YEZZPATH);
		Result<List<AttFile>> resultYEZZ = attFileFeign.all(file);
		if (ResultUtils.isOk(resultYEZZ)) {
			List<AttFile> data = resultYEZZ.getData();
			if (CollectionUtils.isNotEmpty(data)) {
				ducument.setYezzFdId(data.get(0).getFdId());
				ducument.setYezzFileName(data.get(0).getFdFileName());
			}
		}
		// 查询法人身份证
		file.setFdFolderName(PlainTiffDocumentPathPojo.IDENTIFICATIONPATH);
		Result<List<AttFile>> resultIDENTIFICATION = attFileFeign.all(file);
		if (ResultUtils.isOk(resultIDENTIFICATION)) {
			List<AttFile> data = resultIDENTIFICATION.getData();
			if (CollectionUtils.isNotEmpty(data)) {
				ducument.setIdentificationFdId(data.get(0).getFdId());
				ducument.setIdentificationFileName(data.get(0).getFdFileName());
			}
		}
		// 查询法人身份证复印件
		file.setFdFolderName(PlainTiffDocumentPathPojo.IDENTIFICATIONCOPYPATH);
		Result<List<AttFile>> resultIDENTIFICATIONCOPY = attFileFeign.all(file);
		if (ResultUtils.isOk(resultIDENTIFICATIONCOPY)) {
			List<AttFile> data = resultIDENTIFICATIONCOPY.getData();
			if (CollectionUtils.isNotEmpty(data)) {
				ducument.setIdentificationCopyFdId(data.get(0).getFdId());
				ducument.setIdentificationCopyFileName(data.get(0).getFdFileName());
			}
		}
		return ducument;
	}

	public void generatePublicDocument(LegalCaseInfo caseInfo, String stageName, String detailName) {
		// 临时缓存减少单个案子生成不同的文书反复查询数据库 单个案子生成结束手动清空
		PlainTiff plainTiff = getPlainTiffByCaseNo(caseInfo);
		String qszId = queryDateListDetailIdByStageNameAndDetailName(stageName, detailName, caseInfo.getCaseNo());
		PlainTiffDocumentPathPojo queryPlainTiffDocument = queryPlainTiffDocument(plainTiff.getFdId());
		// 先判断原来是否有文件 有的话先删除
		LegalDateListDetail legalDateListDetail = legalDataListDetailMapper.selectByPrimaryKey(qszId);

		String ducumentFdId = "", ducumentName = "";
		if (StringUtils.equals(detailName, "营业执照")) {
			ducumentFdId = queryPlainTiffDocument.getYezzFdId();
			ducumentName = queryPlainTiffDocument.getYezzFileName();
		} else if (StringUtils.equals(detailName, "法定代表人身份证明")) {
			ducumentFdId = queryPlainTiffDocument.getIdentificationFdId();
			ducumentName = queryPlainTiffDocument.getIdentificationFileName();
		} else if (StringUtils.equals(detailName, "法定代表人身份证复印件")) {
			ducumentFdId = queryPlainTiffDocument.getIdentificationCopyFdId();
			ducumentName = queryPlainTiffDocument.getIdentificationCopyFileName();
		}

		if (StringUtils.isNotBlank(ducumentFdId)) {
			// 更新资料清单
			legalDateListDetail.setDocumentName(ducumentName);
			legalDateListDetail.setDocumentPath(ducumentFdId);
			legalDataListDetailMapper.updateByPrimaryKeySelective(legalDateListDetail);
		}
	}
}
